<template>
  <markdown-editor ref="simplemde"
                   :configs="markdownOption"
                   :highlight="true"
                   :value="content"
                   @input="emitInput">
  </markdown-editor>
</template>

<script>
import markdownEditor from 'vue-simplemde'
import { upload } from '@/components/image-input/api'

window.addEventListener('drop', e => {
  e = e || event
  if (e.target.className === 'CodeMirror-scroll') {
    e.preventDefault()
  }
}, false)

export default {
  props: {
    value: String,
    type: {
      type: String,
      default: 'item'
    }
  },
  data () {
    return {
      content: '',
      markdownOption: {
        status: true,
        renderingConfig: {
          codeSyntaxHighlighting: true,
          highlightingTheme: 'atom-one-light'
        }
      }
    }
  },
  mounted () {
    this.content = this.value
    // 拖拽图片
    this.$refs.simplemde.simplemde.codemirror.on('drop', (editor, e) => {
      if (!(e.dataTransfer && e.dataTransfer.files)) {
        this.$message.console.error('该浏览器不支持拖拽')
      }
      let dataList = e.dataTransfer.files
      let imageFiles = []
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].type.indexOf('image') === -1) {
          continue
        }
        imageFiles.push(dataList[i])
      }
      this.uploadImagesFile(imageFiles)
      e.preventDefault()
    })
    // 粘贴图片
    this.$refs.simplemde.simplemde.codemirror.on('paste', (editor, e) => {
      if (!(e.clipboardData && e.clipboardData.items)) {
        this.$message.error('该浏览器不支持粘贴')
        return
      }
      try {
        let dataList = e.clipboardData.items
        let imageFiles = []
        if (dataList && dataList.length) {
          for (let i = 0; i < dataList.length; i++) {
            if (dataList[i].kind !== 'file' || dataList[i].getAsFile().type.indexOf('image') === -1) {
              continue
            }
            imageFiles.push(dataList[i].getAsFile())
          }
        }
        this.uploadImagesFile(imageFiles)
      } catch (e) {
        this.$message.error('只能粘贴图片')
      }
    })
  },
  methods: {
    emitInput (value) {
      this.$emit('input', value)
    },
    uploadImagesFile (files) {
      files.forEach(async (file, i) => {
        try {
          const { url } = await upload({
            type: this.type,
            file: file
          })
          this.content = this.content + `![](${url})` + '\n'
        } catch (error) {
          this.$message.error('上传出现了一些问题')
        }
      })
    }
  },
  components: {
    markdownEditor
  },
  watch: {
    value (val) {
      if (val === this.content) return
      this.content = val
    }
  }
}
</script>

<style lang="scss" scope>
@import "./markdown";
// @import "quill/dist/quill.core.css";
// @import "quill/dist/quill.snow.css";
// @import "quill/dist/quill.bubble.css";
</style>
